package com.ems.service.impl;

import com.ems.entity.RoleMenuEntity;
import com.ems.mapper.RoleMenuMapper;
import com.ems.service.IRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ems.util.SnowflakeIdWorker;
import com.ems.util.StateEnum;
import com.ems.util.StateException;
import com.ems.vo.MenuVo;
import com.ems.vo.RoleMenuVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2023-10-24
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenuEntity> implements IRoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    /**
     * 新增角色对应权限
     * 1、删除已有权限
     * 2、新增新的权限
     * @param roleMenuVo
     * @return
     */
    @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public RoleMenuVo saveRoleMenu (RoleMenuVo roleMenuVo) {
        // 删除绑定角色
        RoleMenuEntity roleMenuEntity = new RoleMenuEntity ();
        roleMenuEntity.setRoleId ( roleMenuVo.getRoleId () );
        roleMenuMapper.deleteSingle ( roleMenuEntity );
        // 新增权限
        for ( MenuVo menuVo : roleMenuVo.getMenuVoList () ) {
            RoleMenuEntity roleMenu = new RoleMenuEntity ();
            roleMenu.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            roleMenu.setRoleId ( roleMenuVo.getRoleId () );
            roleMenu.setMenuId ( menuVo.getId () );
            roleMenu.setCreateTime ( new Date () );
            Integer integer = roleMenuMapper.saveSingle ( roleMenu );
            if ( integer == 0 ) {
                throw new StateException ( StateEnum.INSERT_EXCE );
            }
        }
        return roleMenuVo;
    }
}
